package com.jacen.fzxs.service.app.impl;

import javax.servlet.http.HttpServletRequest;

import org.dom4j.Document;
import org.dom4j.Element;

import com.jacen.fzxs.entity.web.AppEntity;
import com.jacen.fzxs.entity.webservice.Response;
import com.jacen.fzxs.entity.webservice.ResponseState;
import com.jacen.fzxs.exception.ParamException;
import com.jacen.fzxs.exception.PermissionException;
import com.jacen.fzxs.exception.WebException;
import com.jacen.fzxs.service.app.IAppHandlerService;
import com.jacen.fzxs.util.AppEntityFormatUtil;
import com.jacen.fzxs.util.WebServiceUtil;

public abstract class BaseHandlerService implements IAppHandlerService {
	
	protected abstract AppEntity submit(AppEntity appEntity, HttpServletRequest request) throws WebException;

	@Override
	public String handler(Element data, HttpServletRequest request) throws WebException {
		// TODO Auto-generated method stub
		AppEntity appEntity = AppEntityFormatUtil.getInstance().parseData(data);
		AppEntity responseEntity = null;
		Response<AppEntity> response = new Response<AppEntity>();
		try {
			responseEntity = submit(appEntity, request);
		} catch (ParamException e) {
			throw new WebException(returnErrorResponse(response, e, ResponseState.CODE.PARAM_EXCEPTION));
		}  catch (PermissionException e) {
			throw new WebException(returnErrorResponse(response, e, ResponseState.CODE.PERMISSION_EXCEPTION));
		} catch (Exception e) {
			throw new WebException(returnErrorResponse(response, e, ResponseState.CODE.UNKNOWN_EXCEPTION));
		}
		response.setStateCode(ResponseState.CODE.SUCCESS);
		response.setData(responseEntity);
		Document doc = WebServiceUtil.formatResponse(response, AppEntityFormatUtil.getInstance());
		return doc.asXML();
	}

	private String returnErrorResponse(Response<AppEntity> response, Exception e, int errorCode)
			throws WebException {
		response.setStateCode(errorCode);
		ResponseState responseState = response.getResponseState();
		responseState.addError(e.getMessage());
		Document doc = WebServiceUtil.formatResponse(response, null);
		return doc.asXML();
	}
}
